package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"market/marketrpc/internal/svc"
	"market/marketrpc/marketrpc"
	"market/model/mysql"
	"market/model/redis"
	"strconv"
	"time"
)

type PorductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPorductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PorductListLogic {
	return &PorductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PorductListLogic) PorductList(in *marketrpc.PorductListRequest) (*marketrpc.PorductListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}
	size := in.Size
	switch {
	case size > 100:
		size = 100
	case size <= 0:
		size = 10
	}
	offset := (page - 1) * size
	var product []mysql.Products
	itoa := strconv.Itoa(int(offset))
	get := redis.Client.Get("productList" + itoa)
	if get.Val() == "" {
		mysql.DB.Debug().Offset(int(offset)).Limit(int(size)).Where("name like ?", "%"+in.Name+"%").Order("price desc").Find(&product)
		marshal, _ := json.Marshal(&product)
		redis.Client.Set("productList"+itoa, marshal, time.Hour*24)
		fmt.Println("这是mysql")
	} else {
		json.Unmarshal([]byte(get.Val()), &product)
		fmt.Println("这是redis")
	}
	var productlist []*marketrpc.PorductList
	for _, list := range product {
		list := marketrpc.PorductList{
			Name:   list.Name,
			Class:  list.Class,
			Status: list.Status,
			Price:  float32(list.Price),
			Userid: int64(list.UserId),
		}
		productlist = append(productlist, &list)
	}
	return &marketrpc.PorductListResponse{List: productlist}, nil
}
